<template>
  <div class="page-container">
    <div class="card-container with-header">
      <div class="card-header">
        <div class="header-title">{{ isEdit ? '编辑位置' : '添加位置' }}</div>
      </div>
      
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
        class="custom-form"
      >
        <el-form-item label="位置名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入位置名称" />
        </el-form-item>
        
        <el-form-item label="位置类型" prop="typeId">
          <el-select v-model="form.typeId" placeholder="请选择位置类型" class="w-100">
            <el-option
              v-for="item in typeOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item label="位置地址" prop="address">
          <el-input v-model="form.address" placeholder="请输入位置地址" />
        </el-form-item>
        
        <el-form-item label="经纬度" required>
          <el-row :gutter="10">
            <el-col :span="12">
              <el-form-item prop="latitude" class="no-margin">
                <el-input v-model="form.latitude" placeholder="纬度 (如: 21.518411)">
                  <template #prepend>纬度</template>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item prop="longitude" class="no-margin">
                <el-input v-model="form.longitude" placeholder="经度 (如: 111.479953)">
                  <template #prepend>经度</template>
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form-item>
        
        <el-form-item label="封面图" prop="coverImage">
          <el-upload
            class="cover-upload"
            action="/api/upload/image"
            :headers="uploadHeaders"
            :show-file-list="false"
            :on-success="handleCoverSuccess"
            :before-upload="beforeUpload"
          >
            <img v-if="form.coverImage" :src="form.coverImage" class="cover-image">
            <el-icon v-else class="upload-icon"><Plus /></el-icon>
            <div class="upload-tip">点击上传封面图</div>
          </el-upload>
        </el-form-item>
        
        <el-form-item label="图片集">
          <el-upload
            class="gallery-upload"
            action="/api/upload/image"
            :headers="uploadHeaders"
            list-type="picture-card"
            :file-list="fileList"
            :on-success="handleGallerySuccess"
            :on-remove="handleGalleryRemove"
            :before-upload="beforeUpload"
          >
            <el-icon><Plus /></el-icon>
          </el-upload>
        </el-form-item>
        
        <el-form-item label="详细描述" prop="description">
          <el-input
            v-model="form.description"
            type="textarea"
            :rows="5"
            placeholder="请输入详细描述"
          />
        </el-form-item>
        
        <el-form-item label="营业时间" prop="openingHours">
          <el-input v-model="form.openingHours" placeholder="请输入营业时间，如 09:00-18:00" />
        </el-form-item>
        
        <el-form-item label="联系电话" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入联系电话" />
        </el-form-item>
        
        <el-form-item label="是否推荐" prop="isRecommend">
          <el-switch
            v-model="form.isRecommend"
            :active-value="1"
            :inactive-value="0"
            active-text="是"
            inactive-text="否"
          />
        </el-form-item>
        
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        
        <el-form-item>
          <div class="form-btns">
            <el-button type="primary" @click="submitForm">保存</el-button>
            <el-button @click="cancel">取消</el-button>
          </div>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { getLocationTypeList, getLocation, addLocation, updateLocation } from '@/api/location'
import { getToken } from '@/utils/auth'

const route = useRoute()
const router = useRouter()

// 判断是编辑还是新增
const isEdit = computed(() => {
  return route.params.id !== undefined
})

// 表单ref
const formRef = ref(null)

// 表单数据
const form = reactive({
  id: undefined,
  name: '',
  typeId: undefined,
  address: '',
  latitude: '',
  longitude: '',
  coverImage: '',
  images: [], // 图片集
  description: '',
  openingHours: '',
  phone: '',
  isRecommend: 0,
  status: 1
})

// 表单校验规则
const rules = {
  name: [
    { required: true, message: '请输入位置名称', trigger: 'blur' },
    { min: 2, max: 50, message: '位置名称长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  typeId: [
    { required: true, message: '请选择位置类型', trigger: 'change' }
  ],
  address: [
    { required: true, message: '请输入位置地址', trigger: 'blur' }
  ],
  latitude: [
    { required: true, message: '请输入纬度', trigger: 'blur' },
    { pattern: /^-?([1-8]?[0-9](\.[0-9]+)?|90(\.0+)?)$/, message: '请输入有效的纬度值', trigger: 'blur' }
  ],
  longitude: [
    { required: true, message: '请输入经度', trigger: 'blur' },
    { pattern: /^-?((1[0-7][0-9]|[1-9]?[0-9])(\.[0-9]+)?|180(\.0+)?)$/, message: '请输入有效的经度值', trigger: 'blur' }
  ],
  coverImage: [
    { required: true, message: '请上传封面图', trigger: 'change' }
  ]
}

// 位置类型选项
const typeOptions = ref([])

// 图片列表
const fileList = ref([])

// 上传头部
const uploadHeaders = {
  Authorization: `Bearer ${getToken()}`
}

// 获取位置类型列表
const getTypeOptions = async () => {
  try {
    const res = await getLocationTypeList()
    typeOptions.value = res.data
  } catch (error) {
    console.error('获取位置类型失败:', error)
    ElMessage.error('获取位置类型失败')
  }
}

// 获取位置详情
const getDetail = async (id) => {
  try {
    const res = await getLocation(id)
    const data = res.data
    
    // 填充表单
    Object.keys(form).forEach(key => {
      if (data[key] !== undefined) {
        form[key] = data[key]
      }
    })
    
    // 处理图片
    if (data.images && data.images.length > 0) {
      fileList.value = data.images.map((url, index) => {
        return {
          name: `图片${index + 1}`,
          url
        }
      })
    }
  } catch (error) {
    console.error('获取位置详情失败:', error)
    ElMessage.error('获取位置详情失败')
  }
}

// 上传前校验
const beforeUpload = (file) => {
  const isImage = file.type.startsWith('image/')
  const isLt2M = file.size / 1024 / 1024 < 2
  
  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
    return false
  }
  
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过 2MB!')
    return false
  }
  
  return true
}

// 封面上传成功
const handleCoverSuccess = (res, file) => {
  if (res.code === 200) {
    form.coverImage = res.data.url
    ElMessage.success('封面上传成功')
  } else {
    ElMessage.error(res.message || '封面上传失败')
  }
}

// 图片集上传成功
const handleGallerySuccess = (res, file) => {
  if (res.code === 200) {
    fileList.value.push({
      name: file.name,
      url: res.data.url
    })
    form.images.push(res.data.url)
    ElMessage.success('图片上传成功')
  } else {
    ElMessage.error(res.message || '图片上传失败')
  }
}

// 图片集移除
const handleGalleryRemove = (file) => {
  const index = fileList.value.findIndex(item => item.url === file.url)
  if (index !== -1) {
    fileList.value.splice(index, 1)
    form.images.splice(index, 1)
  }
}

// 提交表单
const submitForm = () => {
  formRef.value.validate(async (valid) => {
    if (!valid) return
    
    try {
      if (isEdit.value) {
        await updateLocation(form.id, form)
        ElMessage.success('更新成功')
      } else {
        await addLocation(form)
        ElMessage.success('添加成功')
      }
      
      // 返回列表页
      router.push('/location/list')
    } catch (error) {
      console.error('保存失败:', error)
      ElMessage.error('保存失败')
    }
  })
}

// 取消操作
const cancel = () => {
  router.back()
}

// 初始化
onMounted(async () => {
  await getTypeOptions()
  
  // 如果是编辑模式，获取详情数据
  if (isEdit.value) {
    getDetail(route.params.id)
  }
})
</script>

<style lang="scss" scoped>
.cover-upload {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 360px;
  height: 180px;
  border: 1px dashed $border-color-base;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  
  .cover-image {
    width: 100%;
    height: 100%;
    object-fit: cover;
  }
  
  .upload-icon {
    font-size: 28px;
    color: #8c939d;
  }
  
  .upload-tip {
    color: $text-color-secondary;
    margin-top: 10px;
  }
  
  &:hover {
    border-color: $primary-color;
    
    .upload-icon, .upload-tip {
      color: $primary-color;
    }
  }
}

.no-margin {
  margin-bottom: 0;
}
</style> 